﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ILRuntime.Runtime.Enviorment;
using UnityEditor;
using System.IO;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;

public class Main : MonoBehaviour {

    private string DllPath;
    private string PdbPath;
    //全局只创建一个AppDomain
    AppDomain mAppDomain;

	// Use this for initialization
	void Start () {
        DllPath = "Assets/HotFix/HotFix_Project.dll.txt";
        PdbPath = "Assets/HotFix/HotFix_Project.pdb.txt";

        //StartCoroutine(LoadHotFixAssembly());
        LoadHotFixAssembly();
    }
	
	// Update is called once per frame
	void Update () {
		 
	}

    void LoadHotFixAssembly()
    {
        
        mAppDomain = new AppDomain();
        //读取热更资源的Dll
        TextAsset dllText;
        //pdb文件：调试数据，日志报错
        TextAsset pdbText;
#if UNITY_EDITOR        
        //Debug.Log("path:" + DllPath);
        dllText = AssetDatabase.LoadAssetAtPath<TextAsset>(DllPath);
        pdbText = AssetDatabase.LoadAssetAtPath<TextAsset>(PdbPath);
#else  
        //todo bundle load
#endif
        MemoryStream ms = new MemoryStream(dllText.bytes);
        MemoryStream p = new MemoryStream(pdbText.bytes);
        //dllText.Dispose();
        //pdbText.Dispose();
        mAppDomain.LoadAssembly(ms, p, new ILRuntime.Mono.Cecil.Pdb.PdbReaderProvider());
        //注册
        this.InitializeILRuntime();
        //第一次方法调用
        this.OnHotFixLoaded();
    }

    void InitializeILRuntime()
    {
        //这里做一些ILRuntime的注册
    }
    void OnHotFixLoaded()
    {
        //第一次方法调用

        #region 第一种调用静态方法
        //调用无参数静态方法
        mAppDomain.Invoke("HotFix_Project.InstanceClass", "StaticFunTest", null, null);
        //调用带参数的静态方法
        mAppDomain.Invoke("HotFix_Project.InstanceClass", "StaticFunTest2", null, 123);
        #endregion

        #region 第二种 预先获得IMethod 可以减低每次调用查找方法耗用的时间
        //预先获得IMethod，可以减低每次调用查找方法耗用的时间
        IType type = mAppDomain.LoadedTypes["HotFix_Project.InstanceClass"];
        //根据方法名称和参数个数获取方法
        IMethod method = type.GetMethod("StaticFunTest", 0);
        mAppDomain.Invoke(method, null, null);
        #endregion

    }
}
